#include <iostream>
#include <unordered_set>

using namespace std;

/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* detectCycle(ListNode* head)
    {
        if (head == NULL) {
            return NULL;
        }

        unordered_set<ListNode*> hash;

        auto ret       = hash.emplace(head);
        ListNode* temp = head->next;

        while (temp != NULL) {
            ret = hash.emplace(temp);
            if (ret.second == false) {
                return temp;
            }
            temp = temp->next;
        }
        return NULL;
    }
};